/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/sort-comp */
/**
 * 业务员看板
 */
import React, { Component, PureComponent } from 'react';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import StandardTable from '@/components/StandardTable';
import { Form, Button, DatePicker, Modal, Row, Col, message, Tabs, Input } from 'antd';
import moment from 'moment/moment';
import { connect } from 'dva';
import { debounce, cloneDeep } from 'lodash';
import router from 'umi/router';
import { setLStorage, getLStorage } from '@/utils/utils';
import InfoCheck from '@/components/InfoCheck';
import AddressCascader from '@/components/AddressCascader';
import Exception from '@/components/Exception';
import styles from './style.less';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

@connect(({ allocation, loading, setting, user }) => ({
  currentUser: user.currentUser,
  options: setting.options,
  allocation,
  loading: loading.effects['allocation/getTabList'],
}))
export default class OperatorKanban extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: 'all',
      addressId: [],
      addressOption: [],
      isZyAccount: false,
    };
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/save',
      payload: {
        kanBanList: [],
      },
    });
  }

  onChange = activeKey => {
    const {
      dispatch,
      allocation: { tabList },
    } = this.props;
    const { addressId, isZyAccount } = this.state;
    this.setState({
      activeKey,
    });
    const multBrand = tabList.map(item => item.brand_code);
    const payload = {
      start_scan_time: moment().format('YYYY-MM-DD 00:00:00'),
      end_scan_time: moment().format('YYYY-MM-DD 23:59:59'),
      type: 1,
      cm_name: '',
      brand: activeKey,
      page: 1,
      multBrand: multBrand.join(','),
      n_export: '',
    };
    if (isZyAccount) {
      payload.branch_id = addressId[2];
      payload.branch_level = 3;
    }
    dispatch({
      type: 'allocation/getKanBanList',
      payload,
    });
  };

  onAddressSelect = (value, _, options) => {
    const { addressOption } = this.state;
    const address_options = options[0] ? options : addressOption;
    this.setState({
      addressId: value,
      addressOption: address_options,
    });
  };

  onSwitchAddress = () => {
    const { dispatch } = this.props;
    const { shop_id, addressId, addressOption } = this.state;
    if (addressId.length === 3) {
      message.success('切换成功！');
      setLStorage(shop_id, addressId);
      setLStorage(`${shop_id}_addressOptions`, addressOption);

      dispatch({
        type: 'allocation/getTabList',
        payload: {
          branch_id: addressId[2],
        },
      }).then(res => {
        const { data } = res;
        // 没有快递tab时，清空数据
        if (data.length == 0) {
          dispatch({
            type: 'allocation/save',
            payload: {
              kanBanList: [],
            },
          });
        }
        this.setState({
          activeKey: 'all',
        });
      });
    } else {
      message.warn('请选择具体区域');
    }
  };

  getDeductionInfo() {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/getUserInfo',
    });
  }

  handleInfoReady(data) {
    if (!data.name) return;
    const {
      dispatch,
      options: { key },
    } = this.props;
    const { user_info = {} } = data;
    const { branch = [], shop_id, branchId, branchLevel } = user_info;
    const isTopAccount = branch.length === 0;
    const addressId =
      getLStorage(shop_id) ||
      (isTopAccount ? [] : branch.filter(val => val.level != 0).map(i => i.id));
    const addressOption = getLStorage(`${shop_id}_addressOptions`) || [];
    const currentBranch = isTopAccount ? [] : branch.filter(val => val.level != 0);
    const isZyAccount = key == 'post' || key === 'yjy';
    let payload = {};
    if (branchLevel == 3) {
      this.getDeductionInfo();
    }
    this.setState({
      isZyAccount,
      shop_id,
      addressId,
      addressOption,
      currentBranch,
      companyId: branchId,
      isCountry: branchLevel == '3',
    });

    if (isZyAccount) {
      payload = {
        branch_id: addressId[addressId.length - 1],
      };
      if (payload.branch_id) {
        dispatch({
          type: 'allocation/getTabList',
          payload,
        });
      }
      return;
    }
    dispatch({
      type: 'allocation/getTabList',
      payload,
    });
  }

  render() {
    const {
      activeKey,
      currentBranch,
      isZyAccount,
      addressOption,
      companyId,
      isCountry,
      addressId,
    } = this.state;
    const {
      allocation: {
        tabList,
        deductionInfo: { is_gp },
      },
      options: { key, topAccountTitle },
      currentUser = {},
    } = this.props;
    const { user_info = {} } = currentUser;
    const { branchLevel, branch, shop_id } = user_info;
    const isTopAccount = branchLevel == 0;
    // 防止不更新问题
    const addressIdForProps =
      getLStorage(shop_id) ||
      (isTopAccount ? [] : branch.filter(val => val.level != 0).map(i => i.id));
    const newTabList = [
      {
        brand_name: '总览',
        brand_code: 'all',
      },
      ...tabList,
    ];

    const multBrand = tabList.map(item => item.brand_code);

    if (is_gp == 0 && isZyAccount && isCountry) {
      // 当县级网点无共配权限时，提示
      return (
        <Exception
          type="403"
          title={`您所在的网点尚未开通共配服务，请联系${topAccountTitle}开通！`}
        />
      );
    }

    return (
      <PageHeaderLayout
        title={
          <Row type="flex" justify="space-between" align="middle">
            <Col>业务员看板</Col>
            <Col>
              {isZyAccount ? (
                <Row type="flex" gutter={[10, 0]} align="middle">
                  <Col>
                    <span>县级区域：</span>
                  </Col>
                  <Col>
                    <AddressCascader
                      canChooseParent={false}
                      type="cache"
                      level={3}
                      placeholder="请选择具体县级区域"
                      width={300}
                      request
                      companyId={companyId}
                      branch={currentBranch}
                      value={addressId}
                      onSelect={this.onAddressSelect}
                      optionsFromProps={addressOption}
                      onPopupVisibleChange={this.onPopupVisibleChange}
                    />
                  </Col>
                  <Col>
                    <Button type="primary" onClick={this.onSwitchAddress}>
                      切换
                    </Button>
                  </Col>
                </Row>
              ) : null}
            </Col>
          </Row>
        }
      >
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
        <div className={styles.main}>
          <Tabs onChange={this.onChange} type="card" activeKey={activeKey}>
            {newTabList.map(item => (
              <TabPane tab={item.brand_name} key={item.brand_code}>
                <KanBanPane
                  activeKey={activeKey}
                  multBrand={multBrand}
                  key={item.brand_code}
                  addressId={addressIdForProps}
                  isZyAccount={key == 'post' || key === 'yjy'}
                />
              </TabPane>
            ))}
          </Tabs>
        </div>
      </PageHeaderLayout>
    );
  }
}

@connect(({ allocation, loading }) => ({
  allocation,
  loading: loading.effects['allocation/getKanBanList'],
  resendLoading: loading.effects['allocation/kanBanResend'],
}))
@Form.create()
class KanBanPane extends PureComponent {
  handelSearch = debounce(
    () => {
      this.getList();
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  handleTableChange = debounce(
    pagination => {
      const params = {
        page: pagination.current,
      };
      this.setState({ page: pagination.current }, () => {
        this.getList(params);
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  exportExcel = debounce(
    () => {
      const {
        allocation: { kanBanList = {} },
        isZyAccount,
        addressId,
        dispatch,
      } = this.props;
      const { page } = this.state;
      if (addressId.length < 3 && isZyAccount) {
        message.error('请先选择具体地区');
        return;
      }
      if (kanBanList.list && kanBanList.list.length == 0) {
        message.warning('暂无数据可供导出！');
        return;
      }
      this.getFormValues(value => {
        const data = {
          brand: value.brand,
          start_scan_time: moment(value.start_scan_time).format('YYYY-MM-DD 00:00:00'),
          end_scan_time: moment(value.end_scan_time).format('YYYY-MM-DD 23:59:59'),
          page,
          cm_name: value.cm_name || undefined,
          cm_phone: value.cm_phone || undefined,
          n_export: 'csv',
          multBrand: value.multBrand,
        };
        if (isZyAccount) {
          data.branch_level = 3;
          data.branch_id = addressId[2];
        }
        dispatch({
          type: 'allocation/getKanBanList',
          payload: data,
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor(props) {
    super(props);
    this.state = {
      start: moment()
        .startOf('day')
        .subtract(0, 'days'),
      end: moment()
        .endOf('day')
        .subtract(0, 'days'),
      formValues: {},
      visible: false,
      disabled: false,
      page: 1,
      search: undefined,
      outOfRange: false,
      formDisabled: false,
    };
    this.columns = [
      {
        title: '业务员',
        key: 'name',
        dataIndex: 'name',
        align: 'center',
        render: (text, record) => `${text}-${record.phone}`,
      },
      {
        title: '到件',
        key: 'arrival',
        dataIndex: 'arrival',
        align: 'center',
        children: [
          {
            title: '已推',
            width: 200,
            align: 'center',
            key: 'arrival_success',
            dataIndex: 'arrival[success]',
            render: (text, record) => (
              <a onClick={this.jumpTo.bind(this, { record, type: 'arrive', send_status: '1' })}>
                {text}
              </a>
            ),
          },
          {
            title: '未推',
            width: 200,
            align: 'center',
            key: 'arrival_failed',
            dataIndex: 'arrival[failed]',
            render: (text, record) => (
              <a onClick={this.jumpTo.bind(this, { record, type: 'arrive', send_status: '2' })}>
                {text}
              </a>
            ),
          },
        ],
      },
      {
        title: '派件',
        key: 'delivery',
        dataIndex: 'delivery',
        align: 'center',
        children: [
          {
            title: '已推',
            width: 200,
            align: 'center',
            key: 'delivery_success',
            dataIndex: 'delivery[success]',
            render: (text, record) => (
              <a onClick={this.jumpTo.bind(this, { record, type: 'delivery', send_status: '1' })}>
                {text}
              </a>
            ),
          },
          {
            title: '未推',
            width: 200,
            align: 'center',
            key: 'delivery_failed',
            dataIndex: 'delivery[failed]',
            render: (text, record) => (
              <a onClick={this.jumpTo.bind(this, { record, type: 'delivery', send_status: '2' })}>
                {text}
              </a>
            ),
          },
        ],
      },
      {
        title: '签收',
        key: 'sign',
        dataIndex: 'sign',
        align: 'center',
        children: [
          {
            title: '已推',
            width: 150,
            align: 'center',
            key: 'sign_success',
            dataIndex: 'sign[success]',
            render: (text, record) => (
              <a onClick={this.jumpTo.bind(this, { record, type: 'sign', send_status: '1' })}>
                {text}
              </a>
            ),
          },
          {
            title: '未推',
            width: 150,
            align: 'center',
            key: 'sign_failed',
            dataIndex: 'sign[failed]',
            render: (text, record) => (
              <a onClick={this.jumpTo.bind(this, { record, type: 'sign', send_status: '2' })}>
                {text}
              </a>
            ),
          },
        ],
      },
    ];
  }

  componentDidUpdate(prevProps) {
    const { activeKey: prevActiveKey } = prevProps;
    const {
      activeKey,
      form: { resetFields },
      multBrand,
    } = this.props;
    // 当tab切换时清空form数据
    if (prevActiveKey !== activeKey) {
      resetFields();
    }
    if (multBrand.length == 0) {
      this.setState({
        formDisabled: true,
      });
    } else {
      this.setState({
        formDisabled: false,
      });
    }
  }

  onRangePickerChange(dates) {
    // 当时间不是今天时，禁用重传未推送数据按钮
    const date = dates.map(d => moment(d).format('YYYY-MM-DD'));
    const toDay = moment().format('YYYY-MM-DD');
    const disabled = date.some(value => {
      if (value == toDay) {
        return false;
      }
      return true;
    });
    this.setState({ disabled });
    // 设置日期区间，最大不超过31天
    const section = moment(dates[1]).diff(moment(dates[0]), 'days');
    if (section > 30) {
      message.warn('所选日期区间最大不得超过31天！');
      this.setState({ outOfRange: true });
    } else {
      this.setState({ outOfRange: false });
    }
  }

  getFormValues = then => {
    const { form, activeKey, multBrand } = this.props;
    const { page } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        brand: activeKey,
        page,
        multBrand: multBrand.join(','),
        n_export: '',
      };

      const { date, search } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.start_scan_time = start;
        values.end_scan_time = end;
        delete values.date;
      }
      if (search) {
        if (new RegExp('^[0-9]+$').test(search)) {
          if (new RegExp('^1[3-9][0-9][0-9]{8}$').test(search)) {
            values.cm_phone = search;
          } else {
            message.warning('手机号码格式有误');
            return false;
          }
        } else {
          values.cm_name = search;
        }
      } else {
        values.cm_name = '';
      }
      delete values.search;
      this.setState({
        formValues: values,
      });
      then(values);
    });
  };

  getList(params = {}) {
    const { dispatch, addressId, isZyAccount } = this.props;
    if (isZyAccount) {
      if (addressId.length < 3) {
        message.error('请先选择具体地区');
        return;
      }
      params.branch_id = addressId[2];
      params.branch_level = 3;
    }

    this.getFormValues(res => {
      const data = cloneDeep(res);
      data.start_scan_time = moment(data.start_scan_time).format('YYYY-MM-DD 00:00:00');
      data.end_scan_time = moment(data.end_scan_time).format('YYYY-MM-DD 23:59:59');
      const inMonth = moment(data.end_scan_time).month() == moment(data.start_scan_time).month();
      if (!inMonth) {
        message.warn('不支持跨月查询，请重新选择查询区间');
        return;
      }
      dispatch({
        type: 'allocation/getKanBanList',
        payload: {
          ...data,
          ...params,
        },
      });
    });
  }

  disabledDate = current =>
    current &&
    current >
      moment()
        .endOf('day')
        .subtract(0, 'days');

  dataClick = data => {
    const { form } = this.props;
    const setFieldsValueDate = {
      startDate: moment()
        .startOf('day')
        .subtract(data, 'days'),
      endDate: moment()
        .endOf('day')
        .subtract(data, 'days'),
    };
    if (data == 1) {
      this.setState({ disabled: true });
    } else {
      this.setState({ disabled: false });
    }
    form.setFieldsValue({
      date: [setFieldsValueDate.endDate, setFieldsValueDate.startDate],
    });
  };

  jumpTo({ record, type, send_status }) {
    const { activeKey } = this.props;
    this.getFormValues(formValues => {
      const query = {
        page: 1,
        start_scan_time: formValues.start_scan_time,
        end_scan_time: formValues.end_scan_time,
        courier: record.phone,
        cm_phone: record.phone,
        brand: activeKey,
        send_status,
      };
      router.push({
        pathname: '/Allocation/GunScanRecord',
        hash: `#${type}`,
        query,
      });
    });
  }

  showModal() {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
    });
  }

  reSend(type) {
    // 重传未推送数据
    const {
      dispatch,
      activeKey,
      multBrand,
      allocation: { kanBanList = {} },
      addressId,
      isZyAccount,
    } = this.props;
    const { formValues } = this.state;
    let phone;
    const payload = {
      brand: activeKey,
      phone,
      type,
      multBrand: multBrand.join(','),
      date: moment(formValues.start_scan_time).format('YYYY-MM-DD 00:00:00'),
    };
    if (isZyAccount) {
      if (addressId.length < 3) {
        message.error('请先选择具体地区');
        return;
      }
      payload.branch_id = addressId[2];
      payload.branch_level = 3;
    }
    if (kanBanList.list && kanBanList.list.length > 0) {
      payload.phone = kanBanList.list.map(item => item.phone).join(',');
    } else {
      message.warning('暂无数据！');
      this.showModal();
      return;
    }
    dispatch({
      type: 'allocation/kanBanResend',
      payload,
    }).then(() => {
      this.getList();
      this.showModal();
    });
  }

  blur() {
    const { outOfRange } = this.state;
    if (outOfRange) {
      this.dataClick(0);
    }
  }

  render() {
    const { start, end, visible, disabled, search, formDisabled } = this.state;
    const {
      form: { getFieldDecorator },
      loading,
      allocation: { kanBanList },
      resendLoading,
    } = this.props;
    return (
      <div>
        <Form layout="inline" style={{ marginBottom: 24 }}>
          <FormItem>
            <a
              style={{ marginRight: 20, marginLeft: 20 }}
              className={styles.select_date}
              onClick={() => this.dataClick(0)}
            >
              今日
            </a>
            <a className={styles.select_date} onClick={() => this.dataClick(1)}>
              昨日
            </a>
          </FormItem>
          <FormItem label="扫描时间">
            {getFieldDecorator('date', {
              initialValue: [moment(start), moment(end)],
            })(
              <RangePicker
                style={{ width: '280px' }}
                placeholder={['开始日期', '结束日期']}
                disabledDate={this.disabledDate}
                onChange={this.onRangePickerChange.bind(this)}
                onBlur={this.blur.bind(this)}
              />,
            )}
          </FormItem>
          <FormItem label="业务员">
            {getFieldDecorator('search', {
              initialValue: search,
            })(
              <Input
                style={{ width: '300px' }}
                allowClear
                placeholder="请输入业务员手机号进行搜索"
              />,
            )}
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              disabled={formDisabled}
              onClick={this.handelSearch.bind(this)}
              loading={loading}
            >
              查询
            </Button>
          </FormItem>
          <FormItem>
            <Button
              icon="download"
              type="primary"
              disabled={formDisabled}
              onClick={this.exportExcel.bind(this)}
            >
              导出
            </Button>
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              onClick={this.showModal.bind(this)}
              disabled={disabled || formDisabled}
            >
              重传未推送数据
            </Button>
          </FormItem>
        </Form>
        <StandardTable
          loading={loading}
          rowKey={record => record.phone}
          columns={this.columns}
          data={kanBanList}
          onChange={this.handleTableChange}
        />
        <Modal
          title="重传未推送数据"
          visible={visible}
          onCancel={resendLoading ? null : this.showModal.bind(this)}
          footer={null}
          centered
        >
          {resendLoading && (
            <Row type="flex" justify="center">
              <Col>
                <h3>重传中请勿刷新！</h3>
              </Col>
            </Row>
          )}
          <Row type="flex" justify="space-between">
            <Col>
              <Button
                loading={resendLoading}
                style={{ width: 100 }}
                onClick={this.reSend.bind(this, 5)}
                type="primary"
              >
                到件
              </Button>
            </Col>
            <Col>
              <Button
                loading={resendLoading}
                style={{ width: 100 }}
                onClick={this.reSend.bind(this, 2)}
                type="primary"
              >
                派件
              </Button>
            </Col>
            <Col>
              <Button
                loading={resendLoading}
                style={{ width: 100 }}
                onClick={this.reSend.bind(this, 3)}
                type="primary"
              >
                签收
              </Button>
            </Col>
          </Row>
        </Modal>
      </div>
    );
  }
}
